
import { toRoutes } from '@/utils/permission'
import { getUserRouter } from '@/api/menu'
import { constantRouterMap } from '@/router'
import { getAuthList } from '@/api/api'

const permission = {
  state: {
    // 展示侧边栏的菜单集合
    menuList: [],
    // 从后台获取的前端路由集合
    addRouters: [],
    // 权限API 列表
    authList: []
  },
  mutations: {
    SET_ROUTERS: (state, routers) => {
      state.addRouters = routers
    },
    SET_MENU_LIST: (state, menuList) => {
      state.menuList = menuList
    },
    SET_AUTH_LIST: (state, list) => {
      state.authList = list
    }
  },
  actions: {
    async getUserRouter({ commit, state }) {
      const { err, res } = await getUserRouter(state.token)
      if (err === null) {
        const userRouter = toRoutes(res)
        const menuList = constantRouterMap.concat(userRouter).filter(menu => !menu.hidden)
        commit('SET_ROUTERS', userRouter)
        commit('SET_MENU_LIST', menuList)
      }
    },
    async getAuthList({ commit, state }) {
      const { err, res } = await getAuthList()
      if (err === null) {
        commit('SET_AUTH_LIST', res)
      }
    }
  }
}

export default permission
